package com.luxk.db.server;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class Shutdown {
	
	private ShutdownMode mode = ShutdownMode.NONE;
	private String xmlFilePath = "";
	private String xmlFileName = "server.xml";

	public void exec() throws Exception {

		System.out.println("Server stopping...");

		String serverHome = System.getProperty("server.home");

		if( serverHome == null || "".equals(serverHome)) {
			throw new ServerBuildException("Property server.home not found");
		}

		System.setProperty( "user.dir", serverHome );

		xmlFilePath = serverHome + File.separator +
				"conf" + File.separator +
				xmlFileName;
		
		ServerInstanceBuilder builder = new ServerInstanceBuilder();
		Server server = builder.build(xmlFilePath);

		try {
			Socket socket = new Socket("127.0.0.1", server.getPort());
			OutputStream out = socket.getOutputStream();
			String shutdown = server.getShutdownCommand();
			for( int i = 0; i < shutdown.length(); i++ )
				out.write( shutdown.charAt(i) );
			out.flush();
			out.close();
			socket.close();
		} catch(IOException e) {
			throw e;
		}
	}
	
	public void useage() {
		System.out.println("Useage : Shutdown [mode]");
		System.out.println("  mode IMMEDIATE|ABORT|ABNORMAL : Server shutdown mode");
	}

	public void processArgs(String[] args) {
		
		if(args.length > 0) {
			for(ShutdownMode m: ShutdownMode.values())
				if(m.getStrVal().equalsIgnoreCase(args[0])) {
					this.mode = m;
					return;
				}
		} else {
			this.mode = ShutdownMode.NORMAL;
		}
	}
	
	public static void main(String[] args) {
		try {
			Shutdown shutdown = new Shutdown();
			shutdown.processArgs(args);
			if(shutdown.mode != ShutdownMode.NONE) {
				shutdown.exec();
			} else {
				shutdown.useage();
			}

			System.exit(0);

		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
